<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AgentRefund as Service;
use app\common\model\Export;
use app\model\AgentRefund as Model;
use app\model\AgentRefundConfig;
use think\Request;
use think\facade\Db;

class AgentRefund extends Controller
{
    /**
     * @api {GET} /admin/agentRefund/ 申请退款列表
     * @apiDescription 申请退款列表
     * @apiName agentRefundList 申请退款列表
     * @apiGroup Admin2_0
     * @apiParam {Number=1,2,3,4,5} [status=0] tab上的状态
     * @apiParam {String} [startValue] 申请开始时间
     * @apiParam {String} [endValue] 申请结束时间
     * @apiParam {Number} [page=1] 页码
     * @apiParam {Number} [list_rows=10] 分页大小
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function index(Request $request)
    {
        // step 构造查询
        $modelQuery = Model::withJoin(['agent' => function ($query) {
            $query->WithField(['agent.company_name' => 'company_name', 'agent.username' => 'username']);
        }], 'left');
        $tableName = $modelQuery->getTable();
        $tableName = array_pop($tableName);

        if ($request->param('state')) {
            $modelQuery = $modelQuery->where($tableName.'.state', $request->param('state'));
        }
        if ($request->param('type')) {
            $modelQuery = $modelQuery->where($tableName.'.type', $request->param('type'));
        }
        if ($request->has('startValue')) {
            $modelQuery = $modelQuery->where($tableName.'.created_at', '>=', $request->param('startValue'));
        }
        if ($request->has('endValue')) {
            $modelQuery = $modelQuery->where($tableName.'.created_at', '<=', $request->param('endValue') . ' 23:59:59');
        }
        if ($request->has('keyword')) {
            $modelQuery = $modelQuery->where('agent.username|agent.company_name|agent_refund.alipay|agent_refund.wechat|agent_refund.mobile', 'like', '%'.$request->param('keyword').'%');
        }

        // 分别处理导出和 列表查询
        if (!$request->has('is_export')) {
            $list = $modelQuery->order($tableName.'.id desc')->paginate($this->getPaginate());
        } else {
            $stateArr = Model::$state;
            $list = $modelQuery->order($tableName.'.id desc')->select()->toArray();
            $res = [];
            $type = $request->param('type', 1);
            if ($type == 1) {
                // 支付宝退款
                $title = ['退款方式', '代理商名称', '公司名称', '申请金额', '支付宝', '微信', '联系手机', '退款状态', '申请时间', '用户备注', '审核备注'];
                foreach ($list as $v) {
                    $res[] = [
                        '支付宝',
                        $v['username'],
                        $v['company_name']."\t",
                        fen2yuan($v['amount']).'',
                        $v['alipay'],
                        $v['wechat'],
                        $v['mobile'],
                        $stateArr[$v['state']] ?? '申请中',
                        $v['created_at'],
                        $v['user_remark'],
                        $v['remark'],
                    ];
                }
                $name = '支付宝退款列表';
            } else {
                // 银行卡退款
                $title = ['退款方式', '代理商名称', '公司名称', '申请金额', '银行卡号', '户名', '开户行', '联系手机', '退款状态', '申请时间', '用户备注', '审核备注'];
                foreach ($list as $v) {
                    $res[] = [
                        '银行卡',
                        $v['username'],
                        $v['company_name']."\t",
                        fen2yuan($v['amount']).'',
                        $v['bank_card_no'],
                        $v['bank_username'],
                        $v['bank_name'],
                        $v['mobile'],
                        $stateArr[$v['state']] ?? '申请中',
                        $v['created_at'],
                        $v['user_remark'],
                        $v['remark'],
                    ];
                }
                $name = '银行卡退款列表';
            }
            unset($list);
            $export = new Export;
            return $export->downloadExcel($title, $res, $name);
        }

        if (!$list->isEmpty()) {
            $list = $list->hidden(['agent']);
        }
        $list = $list->toArray();
        $list['total_apply_amount'] = $modelQuery->sum('amount');
        $list['total_success_amount'] = $modelQuery->whereIn($tableName.'.state', [2, 6])->sum('amount');
        /*
        $list['total_apply_amount'] = Db::name('agent_refund')
            // ->where('state', '!=', 4)
            ->sum('amount');
        $list['total_success_amount'] = Db::name('agent_refund')
            ->whereIn('state', [2, 6])
            ->sum('amount');
        */

        return success('操作成功', $list);
    }

    /**
     * @api {GET} /admin/agentRefund/accept 审核通过退款
     * @apiDescription 审核通过退款
     * @apiName agentRefundAccept 审核通过退款
     * @apiGroup Admin2_0
     * @apiParam {Number} id
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function accept(Request $request)
    {
        if (!$id = $request->param('id', 0)) {
            return fail('非法参数');
        }
        $res = Service::make()->accept($id);
        if ($res['code']) {
            return fail($res['msg']);
        }

        return success();
    }

    /**
     * @api {GET} /admin/agentRefund/reject 拒绝退款申请
     * @apiDescription 拒绝退款申请
     * @apiName agentRefundReject 拒绝退款申请
     * @apiGroup Admin2_0
     * @apiParam {Number} id
     * @apiParam {String} remark 拒绝理由
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function reject(Request $request)
    {
        $rules = [
            'id' => 'require',
            'remark' => 'require',
        ];
        $messages = [
            'require' => '缺少必要参数',
            'remark.require' => '请填写拒绝理由',
        ];
        $param = $request->only(['id', 'remark']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        $res = Service::make()->reject($param);
        if ($res['code']) {
            return fail($res['msg']);
        }

        return success();
    }

    /**
     * @api {GET} /admin/withdraw/getConfig 退款配置获取
     * @apiDescription 退款配置获取
     * @apiName 退款配置获取
     * @apiGroup Admin2_0
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function getConfig()
    {
        $data = AgentRefundConfig::where('agent_id', 0)->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = ['id' => 0];
        }

        return success('', $data);
    }

    /**
     * @api {POST} /admin/withdraw/setConfig 配置退款
     * @apiDescription 配置退款
     * @apiName 配置退款
     * @apiParam {Number} id id，根据 getConfig获取到的id
     * @apiParam {Number} min_amount 最低退款金额 单位元
     * @apiParam {Number} day_max_freq 单日最大退款次数
     * @apiParam {Number} rate 退款手续费
     * @apiParam {Number} auto_aprove_max 自动审核金额封顶金额
     * @apiParam {String} [memo]  备注
     * @apiGroup Admin2_0
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function setConfig(Request $request)
    {
        $rules = [
            'rate' => 'require|float|egt:0',
            'auto_aprove_max' => 'require|float|gt:0',
            'interval_day' => 'require|number|gt:0',
        ];
        $messages = [
            'interval_day.require' => '请填写单日最多退款次数',
            'interval_day.number' => '单日最多退款次数只能是整数',
            'interval_day.gt' => '单日最多退款次数必须大于 0',
            'auto_aprove_max.require' => '请填写自动审核金额',
            'auto_aprove_max.float' => '自动审核金额只能是数字',
            'auto_aprove_max.gt' => '自动审核金额必须大于 0',
            'rate.require' => '请填写退款手续费',
            'rate.float' => '退款手续费只能是数字',
            'rate.egt' => '退款手续费不能小于 0',
        ];
        $config = $request->only(['interval_day', 'rate', 'auto_aprove_max', 'memo' => '']);
        if ($msg = dmjValidate($rules, $messages, $config)) {
            return fail($msg);
        }

        $id = $request->param('id', 0);
        if (!$id) {  // 新建
            $configModel = new AgentRefundConfig();
        } else {
            $configModel = AgentRefundConfig::find($id);
            if (!$configModel) {
                return fail('数据不存在，请刷新或者联系我们');
            }
        }

        foreach ($config as $k => $v) {
            $configModel->{$k} = $v;
        }
        if (!$configModel->save()) {
            return fail('操作失败，请重试或者联系我们');
        }

        return success();
    }
}
